package 中等;

import java.util.Arrays;

public class 最接近的三数之和 {

    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        int start, end, res = 10000;
        for (int i = 0; i < n-2; i++) {
            int a = nums[i];
            start = i + 1;
            end = n - 1;
            while (end > start){
                int sum = nums[end] + nums[start] + a;
                if (sum > target){
                    while (end > start && nums[end] == nums[--end]){

                    }

                }else if (sum < target){
                    while (end > start && nums[start] == nums[++start]){

                    }
                }else {
                    return target;
                }
                if (Math.abs(res - target) > Math.abs(sum - target)){
                    res = sum;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {

        int[] nums  = {-3,-2,-5,3,-4};
        int target = -1;
        System.out.println(threeSumClosest(nums, target));
    }
}
